<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #filter>
        <a-button
          :type="dataRef.linkCond && dataRef.linkCond.length ? 'primary' : 'default'"
          @click="handleConfiguration"
          title="当满足条件时，显示链接"
        >
          配置
        </a-button>
      </template>
      <template #event>
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="linkEventOptions"
              v-model:value="dataRef['linkEvent']"
              placeholder="请选择"
              style="width: 120px"
              showSearch
              optionFilterProp="label"
              :get-popup-container="getPopupContainer"
            />
            <Select
              v-if="dataRef['linkEvent'] == 'module'"
              style="flex: 1"
              :options="moduleList"
              v-model:value="dataRef['moduleCode']"
              placeholder="请选择"
              showSearch
              optionFilterProp="name"
              :field-names="{ label: 'name', value: 'code' }"
              :get-popup-container="getPopupContainer"
            />
            <template v-if="dataRef['linkEvent'] == 'flow'">
              <TreeSelect
                class="w-50"
                :tree-data="treeData"
                :field-names="{ label: 'name', value: 'code', key: 'code' }"
                :show-search="true"
                treeNodeFilterProp="name"
                v-model:value="dataRef['flowTypeCode']"
                :get-popup-container="getPopupContainer"
              />
              <!-- params -->
              <SettingOutlined title="映射字段" class="cursor-pointer" @click="handleParams" />
            </template>
            <template v-if="dataRef['linkEvent'] == 'moduleAdd'">
              <Select
                style="flex: 1"
                :options="moduleList"
                v-model:value="dataRef['moduleCode']"
                placeholder="请选择"
                showSearch
                optionFilterProp="name"
                :field-names="{ label: 'name', value: 'code' }"
                :get-popup-container="getPopupContainer"
              />
              <Select
                :options="modeList"
                v-model:value="dataRef['mode']"
                placeholder="请选择"
                style="flex: 1"
                showSearch
                optionFilterProp="label"
                :get-popup-container="getPopupContainer"
              />
            </template>

            <Input
              v-model:value="dataRef['linkHref']"
              placeholder="请输入"
              title="注：点击事件方法中如有双引号将会被自动替换为单引号"
              style="flex: 1"
              v-if="dataRef['linkEvent'] == 'link' || dataRef['linkEvent'] == 'click'"
            />
          </div>
        </FormItemRest>
      </template>
      <template #role>
        <SelectRoleInput
          :roleCodes="dataRef.roleCodes"
          v-model:value="dataRef.roleDescs"
          @change="(val, node) => handleRoleNames(val, node)"
          title="为空则表示角色不限，均可以看见此按钮"
        />
      </template>
    </BasicForm>
    <ConfigurationModal
      @register="registerConfigurationModal"
      @success="handleSuccessConfigurationModal"
      :zIndex="2000"
    />
    <FieldMappingModal
      @register="registerFieldMappingModal"
      @success="handleSuccessFieldMappingModal"
      :zIndex="2000"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted, inject } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, linkEventOptions, makeBtnJson, loadProp, modeList } from './common.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFormGetFields, getFlowGetDirTreeAll } from '/@/api/flowManage/flowManage';
  import { Form, Input, Select, TreeSelect } from 'ant-design-vue';
  import { TreeItem } from '/@/components/Tree';
  import { SettingOutlined } from '@ant-design/icons-vue';
  import { SelectRoleInput } from '/@/components/CustomComp';
  import FieldMappingModal from '../../setupComponent/operationColumnLink/FieldMappingModal.vue';
  import ConfigurationModal from '../../configuration/index';
  import { getRoleNames, getModulesAll } from '/@/api/system/system';

  export default defineComponent({
    name: 'CommonDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      FormItemRest: Form.ItemRest,
      SelectRoleInput,
      Input,
      Select,
      TreeSelect,
      SettingOutlined,
      FieldMappingModal,
      ConfigurationModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const { createMessage } = useMessage();
      const moduleCode = ref('');
      const formCode = ref('');
      const moduleList = ref<Recordable[]>([]);
      const position = ref('');

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        console.log('data', data);
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        moduleCode.value = data?.moduleCode;
        formCode.value = data?.formCode;
        position.value = data?.position; // 当此抽屉用于表单时为 form
        dataRef.value = {};
        const record = data?.record;
        getFormGetFieldsData();
        if (unref(isUpdate)) {
          if (record) {
            dataRef.value = loadProp(record);
            if (dataRef.value.roleCodes) {
              const res = await getRoleNames({ codes: dataRef.value['roleCodes'] });
              dataRef.value['roleDescs'] = res.join(',');
            }
          }
          console.log('dataRef.value', dataRef.value);
          setFieldsValue({
            ...dataRef.value,
          });

          console.log('position', position.value);
          if (position.value === 'form') {
            updateSchema([
              {
                field: 'btnId',
                ifShow: false,
                required: false,
              },
            ]);
            updateSchema([
              {
                field: 'title',
                ifShow: false,
                required: false,
              },
            ]);
            updateSchema([
              {
                field: 'linkName',
                ifShow: false,
                required: false,
              },
            ]);
            updateSchema([
              {
                field: 'enabled',
                ifShow: false,
              },
            ]);
          }
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      const formGetFieldsData = ref([]);
      //获取数据
      const getFormGetFieldsData = () => {
        formGetFieldsData.value = [];
        try {
          if (!formCode.value) return;
          getFormGetFields({ formCode: formCode.value }).then((res) => {
            formGetFieldsData.value = res || [];
            formGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
          });
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };
      const [registerConfigurationModal, { openModal: openConfiguration }] = useModal();
      //组合条件配置
      const handleConfiguration = () => {
        openConfiguration(true, {
          list: dataRef.value.linkCond || [],
          formGetFieldsData: formGetFieldsData.value,
        });
      };

      const handleSuccessConfigurationModal = ({ value }) => {
        dataRef.value.linkCond = value;
      };

      //角色回调
      const handleRoleNames = (val, node) => {
        const { dataRef: newDataRef } = node;
        dataRef.value.roleDescs = val;
        dataRef.value.roleCodes = newDataRef['codes'];
      };

      const [registerFieldMappingModal, { openModal }] = useModal();
      //映射字段
      const handleParams = () => {
        if (!dataRef.value['flowTypeCode']) {
          createMessage.warning('请选择流程');
          return;
        }
        openModal(true, {
          formCode: formCode.value,
          flowTypeCode: dataRef.value.flowTypeCode,
          params: dataRef.value['params'],
        });
      };
      //映射回调
      const handleSuccessFieldMappingModal = ({ params }) => {
        dataRef.value['params'] = params;
        console.log("dataRef.value['params']", dataRef.value['params']);
      };

      async function handleSubmit() {
        try {
          console.log('handleSubmit dataRef', dataRef.value);
          const values = await validate();
          console.log('handleSubmit values', values);
          let formData = Object.assign({}, dataRef.value, values);
          console.log('handleSubmit formData', formData);
          const data = makeBtnJson(formData, position.value);
          if (data!.isAlow) {
            return;
          }
          formData = data!.record;
          // formData.moduleCode = moduleCode.value;
          console.log('handleSubmit formData2', formData);
          // if (formData['linkEvent'] == 'flow' && !formData['flowTypeCode']) {
          //   createMessage.warning('请选择流程');
          //   return;
          // }
          // setDrawerProps({ confirmLoading: true });
          closeDrawer();
          emit('success', formData);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      const treeData = ref<TreeItem[]>([]);
      const fetch = async () => {
        const data = (await getFlowGetDirTreeAll()) || [];
        treeData.value = setChildren(data);
        getModulesAllData();
      };

      function setChildren(node) {
        node.forEach((item) => {
          item.key = item.code;
          item.value = item.code;
          item.title = item.name;
          item.disabled = item.layer == 3 ? false : true;
          if (item.children && Array.isArray(item.children) && item.children.length > 0) {
            item.isLeaf = false;
            setChildren(item.children);
          } else {
            item.isLeaf = true;
          }
        });
        return node;
      }

      //获取所有模块
      const getModulesAllData = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

      onMounted(fetch);
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        isUpdate,
        registerConfigurationModal,
        handleSuccessConfigurationModal,
        handleConfiguration,
        dataRef,
        handleRoleNames,
        linkEventOptions,
        treeData,
        registerFieldMappingModal,
        handleSuccessFieldMappingModal,
        handleParams,
        moduleList,
        getPopupContainer,
        modeList,
      };
    },
  });
</script>
